package org.zjt.io;

import java.io.FileDescriptor;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * Description:
 *
 *      大文件的切割器（零拷贝）
 *
 * @author juntao.zhang
 * Date: 2018-10-26 9:24 PM
 * @see
 */
public class BigFileSpliter {


    public static void main(String[] args)throws Exception {
        RandomAccessFile randomAccessFile =
                new RandomAccessFile("/Users/juntao.zhang/dev/workspace/mywork/demo/open-platform/src/main/java/org/zjt/open/platform/src/resource/access_138.txt","r");

        try (FileChannel channel = randomAccessFile.getChannel()) {
            long length = randomAccessFile.length();
            long chunk = 2 << 10 << 10;
            long size = length % chunk == 0 ? length / chunk : length / chunk + 1;

            for (int i = 0; i < size; i++) {
                try (RandomAccessFile target = new RandomAccessFile("/Users/juntao.zhang/dev/workspace/myproject/java-basic/src/main/java/org/zjt/io/data_" + i + ".txt", "rw")) {

                    long offset = i * chunk;
                    channel.transferTo(offset, chunk, target.getChannel());
                }
            }
        }
    }
}
